# from django.shortcuts import render, redirect
# from app01 import models
# from app01.utils.pagination import Pagination
# from app01.utils.form import PrettyEditModelForm, PrettyModelForm, UserModelFrom
#
#
# # Create your views here.
#
# def depart_list(request):
#     """部门列表"""
#     # 1，去数据库中获取所有的部门列表
#     queryset = models.Department.objects.all()
#
#     page_object = Pagination(request, queryset, page_size=2)
#     context = {
#         'queryset': page_object.page_queryset,
#         'page_string': page_object.html()
#     }
#
#     return render(request, 'depart_list.html', context)
#
#
# def depart_add(request):
#     """新增部门"""
#     if request.method == "GET":
#         return render(request, 'depart_add.html')
#
#     # 获取用户post提交的的数据
#     title = request.POST.get('title')
#     # 获取到后保存到数据库
#     models.Department.objects.create(title=title)
#
#     # 重定向回列表页面
#     return redirect("/depart/list/")
#
#
# def depart_delete(request):
#     """删除功能"""
#     # 获取id
#     nid = request.GET.get("nid")
#     # 删除
#     models.Department.objects.filter(id=nid).delete()
#     # 重定向回列表页面
#     return redirect("/depart/list/")
#
#
# # nid参数是视图函数传来的值
# def depart_edit(request, nid):
#     """修改"""
#     if request.method == 'GET':
#         # 根据nid就可以获取那行的数控
#         # first() 当只向获取第一个是不用在提起【获取nid那行
#         row_object = models.Department.objects.filter(id=nid).first()
#
#         return render(request, 'depart_edit.html', {'row_object': row_object})
#
#     # 获取用户提交的title【标题
#     title = request.POST.get('title')
#     # 根据id找到数据库那行的数据并进行更新
#     models.Department.objects.filter(id=nid).update(title=title)
#
#     # 重定向回列表页面
#     return redirect("/depart/list/")
#
#
# def user_list(request):
#     """用户管理"""
#
#     # 获取数据库用户信息
#     queryset = models.UserInfo.objects.all()
#     """
#     for obj in queryset:
#         print(
#             obj.id,
#             obj.name,
#             obj.password,
#             obj.age,
#             obj.account,
#             obj.create_time.strftime("%Y-%m-%d"),   # 转换为字符串并去年月日
#             obj.get_gender_display(),   # 前面数据库封装好了的1代表男 2代表女
#             obj.depart.title    # 跨表拿到对应的数据
#         )
#     """
#     page_object = Pagination(request, queryset, page_size=2)
#     context = {
#         'queryset': page_object.page_queryset,
#         'page_string': page_object.html(),
#
#     }
#     return render(request, 'user_list.html', context)
#
#
# def user_add(request):
#     # 判断是什么请求 get
#     if request.method == "GET":
#         context = {
#             # 拿到在到html中输出
#             'gender_choices': models.UserInfo.gender_choices,
#             'depart_list': models.Department.objects.all()
#         }
#         return render(request, 'user_add.html', context)
#     # 否则是post请求
#     # 拿到用户输入post的数据
#     name = request.POST.get('name')
#     password = request.POST.get('password')
#     age = request.POST.get('age')
#     account = request.POST.get('account')
#     create_time = request.POST.get('create_time')
#     gender = request.POST.get('gender')
#     depart_id = request.POST.get('depart_id')
#
#     # 保存到数据库
#     models.UserInfo.objects.create(
#         name=name,
#         password=password,
#         age=age,
#         account=account,
#         create_time=create_time,
#         gender=gender,
#         depart_id=depart_id
#     )
#     # 重定向用户列表
#     return redirect('/user/list')
#
#
# # +++++++++++++++++++++++++++++++ 基于ModelFrom 实列 +++++++++++++++++++++++++++++++
#
#
# def user_model_from_add(request):
#     """添加用户 基于ModelFrom"""
#     if request.method == "GET":
#         form = UserModelFrom()
#         return render(request, 'user_model_from_add.html', {'form': form})
#
#     # POST 提交
#     # request.POST用户提交的所有数据给到UserModelFrom
#     # 在UserModelFrom会去fields取到每一个字段后
#     form = UserModelFrom(data=request.POST)
#     # 拿到字段后会对其逐一校验
#     if form.is_valid():
#         # 如果数据检验正确 保存到数据库
#         # {'name': '阿猴鸡', 'password': '14564', 'age': 1, 'account': Decimal('244156'), 'create_time': datetime.datetime(2013, 12, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'gender': 1, 'depart': <Department: 企划部的>}
#         # # 常规保存法
#         # cleaned_data = form.cleaned_data  # 校验成功得到的数据
#         # models.UserInfo.objects.create(name=cleaned_data['name'])
#         form.save()  # modelform提供的保存方法
#         return redirect('/user/list')  # 保存成功重定向回用户列表页面
#     else:
#         # 检验失败 在页面显示错误信息
#         # print(form.errors)  # 校验失败的到所有的错误信息
#         return render(request, 'user_model_from_add.html', {'form': form})
#
#
# def user_edit(request, nid):
#     """编辑用户"""
#
#     row_object = models.UserInfo.objects.filter(id=nid).first()
#
#     if request.method == 'GET':
#         # 根据id去数据库获取要编辑的数据(对象)
#         # row_object = models.UserInfo.objects.filter(id=nid).first()
#         # instance=row_object 加上这个modelform会把默认值显示在输入框
#         form = UserModelFrom(instance=row_object)
#         return render(request, 'user_edit.html', {"form": form})
#
#     # post
#     # row_object = models.UserInfo.objects.filter(id=nid).first() # 拿到对应的行 对象
#     form = UserModelFrom(data=request.POST, instance=row_object)  # instance=rew_object 没有就是添加，写了就是更新
#     if form.is_valid():
#         # 默认保存的是用户输入的数据
#         # 如果有些不是用户输入的数据，也要保存到数据库 【model = models.UserInfo 规定的表中
#         # form.instance.数据表字段名 = 某个想要保存的数据
#         form.save()
#         return redirect('/user/list/')
#     return render(request, 'user_edit.html', {"form": form})
#
#
# def user_delete(request, nid):
#     models.UserInfo.objects.filter(id=nid).delete()
#     return redirect('/user/list/')
#
#
# def pretty_list(request):
#     """靓号列表"""
#     # 实验数据
#     # for i in range(300):
#     #     if i < 10:
#     #         models.PrettyNum.objects.create(
#     #             mobile=f'1771233597{i}',
#     #             price=1+i,
#     #             level=3,
#     #             status=1
#     #         )
#     #     elif i > 10 and i < 100:
#     #         models.PrettyNum.objects.create(
#     #             mobile=f'177123359{i}',
#     #             price=1 + i,
#     #             level=2,
#     #             status=1
#     #         )
#     #     else:
#     #         models.PrettyNum.objects.create(
#     #             mobile=f'17712335{i}',
#     #             price=1 + i,
#     #             level=2,
#     #             status=2
#     #         )
#
#     data_dict = {}
#     search_data = request.GET.get('q', '')
#     if search_data:
#         data_dict['mobile__contains'] = search_data
#
#     # res = models.PrettyNum.objects.filter(**data_dict)
#     # 1，从数据库中拿到所欲数据
#     #   .order_by("-level") 排序 加上减号表示倒序
#     # queryset = models.PrettyNum.objects.all().order_by("-level")
#
#     queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
#     page_object = Pagination(request, queryset)
#
#     page_queryset = page_object.page_queryset
#     page_string = page_object.html()
#
#     context = {
#         'search_data': search_data,
#
#         "queryset": page_queryset,  # 分完页的数据
#         'page_string': page_string  # 生成的页码
#     }
#
#     # 把数据传到html页面
#     return render(request, 'pretty_list.html', context)
#
#     # 根据用户想访问的页数 算出起始和结束
#     # page = int(request.GET.get('page', 1))
#     # page_size = 10
#     # start = (page - 1) * page_size
#     # end = page * page_size
#     # queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start: end]
#     #
#     # # 数据总条数
#     # total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
#     # # 总页码
#     # total_page_count, div = divmod(total_count, page_size)  # (除数，被除数) 得（商，余数）
#     # if div:  # 判断余数是否大于1 大于1 页码数加1
#     #     total_page_count += 1
#
#     # # 计算出应该显示的页码【当前页的前后五页
#     # plus = 5
#     #
#     # # 判断数据库中的数据比较少的时候 没有到达11页那就不同
#     # if total_page_count <= 2 * plus + 1:
#     #     start_page = 1
#     #     end_page = total_page_count
#     # else:
#     #     # 数据库中的数据超过11页
#     #     # 当前页数大于5时（小的极值）
#     #     if page <= plus:
#     #         start_page = 1
#     #         end_page = 2 * plus + 1
#     #     else:
#     #         # 当后页数超过总页数时
#     #         if (page + plus) > total_page_count:
#     #             start_page = total_page_count - 2 * plus
#     #             end_page = total_page_count
#     #         else:
#     #             start_page = page - plus
#     #             end_page = page + plus
#     #
#     #     # 我写的垃圾逻辑
#     #     # start_page = page - plus
#     #     # if start_page <= 0:
#     #     #     start_page = 1
#     #     # end_page = page + plus
#     #     # if end_page >= total_page_count:
#     #     #     end_page = total_page_count + 1
#     #
#     # # 页码
#     # page_str_list = []
#     #
#     # page_str_list.append('<li><a href="/pretty/list/?page=1">首页</a></li>')
#     #
#     # # 上一页
#     # if page > 1:
#     #     prev = '<li><a href="/pretty/list/?page={}">«</a></li>'.format(page - 1)
#     # else:
#     #     prev = '<li><a href="/pretty/list/?page={}">«</a></li>'.format(1)
#     # page_str_list.append(prev)
#     # # le = len(models.PrettyNum.objects.all())
#     # # for i in range(1, le // 10 + 2):
#     # # 列表页面（数字）
#     # for i in range(start_page, end_page + 1):
#     #     # 给当前页加上标志
#     #     if i == page:
#     #         ele = '<li class="active"><a href="/pretty/list/?page={}">{}</a></li>'.format(i, i)
#     #     else:
#     #         ele = '<li><a href="/pretty/list/?page={}">{}</a></li>'.format(i, i)
#     #     page_str_list.append(ele)
#     #
#     # # 下一页
#     # if page < total_page_count:
#     #     prev = '<li><a href="/pretty/list/?page={}">»</a></li>'.format(page + 1)
#     # else:
#     #     prev = '<li><a href="/pretty/list/?page={}">»</a></li>'.format(total_page_count)
#     # page_str_list.append(prev)
#     #
#     # # 尾页
#     # page_str_list.append('<li><a href="/pretty/list/?page={}">尾页</a></li>'.format(total_page_count))
#     #
#     # # 输入页码
#     # search_string = """
#     #         <li style="float: right">
#     #             <form class="form-inline" method="get">
#     #                 <div class="form-group">
#     #                     <input style="width: 80px" type="text" name="page" class="form-control" id="exampleInputEmail3"
#     #                            placeholder="输入页码">
#     #                 </div>
#     #                 <button type="submit" class="btn btn-default">
#     #                     <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
#     #                 </button>
#     #             </form>
#     #         </li>
#     # """
#     # page_str_list.append(search_string)
#     # page_string = mark_safe("".join(page_str_list))
#
#     # 把数据传到html页面
#     # return render(request, 'pretty_list.html', {
#     #     "queryset": page_queryset,
#     #     'search_data': search_data,
#     #     'page_string': page_string
#     # })
#
#
# def pretty_add(request):
#     if request.method == "GET":
#         form = PrettyModelForm()
#         return render(request, 'pretty_add.html', {'form': form})
#
#     # 提交post
#     form = PrettyModelForm(data=request.POST)
#     if form.is_valid():
#         form.save()  # 保存
#         return redirect('/pretty/list/')
#     # 检验失败 在页面显示错误信息
#     # print(form.errors)  # 校验失败的到所有的错误信息
#     else:
#         return render(request, 'pretty_add.html', {'form': form})
#
#
# def pretty_edit(request, nid):
#     """编辑靓号"""
#     # 1 通过id拿到对象
#     row_object = models.PrettyNum.objects.filter(id=nid).first()
#
#     if request.method == 'GET':
#         # 根据id去数据库获取要编辑的数据(对象)
#         # row_object = models.UserInfo.objects.filter(id=nid).first()
#         # instance=row_object 加上这个modelform会把默认值显示在输入框
#         form = PrettyEditModelForm(instance=row_object)
#         return render(request, 'pretty_edit.html', {"form": form})
#
#     # post
#     # row_object = models.UserInfo.objects.filter(id=nid).first() # 拿到对应的行 对象
#     form = PrettyModelForm(data=request.POST, instance=row_object)  # instance=rew_object 没有就是添加，写了就是更新
#     if form.is_valid():
#         # 默认保存的是用户输入的数据
#         # 如果有些不是用户输入的数据，也要保存到数据库 【model = models.UserInfo 规定的表中
#         # form.instance.数据表字段名 = 某个想要保存的数据
#         form.save()
#         return redirect('/pretty/list/')
#     # 否则回到有错误提示的页面
#     return render(request, 'user_edit.html', {"form": form})
#
#
# def pretty_delete(request, nid):
#     models.PrettyNum.objects.filter(id=nid).delete()
#     return redirect('/pretty/list/')
